package chatroom921_homework;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Server {
    private ServerSocket serverSocket;
    //private List<PrintWriter> allout = new ArrayList();
    private Map<String,PrintWriter> allout = new HashMap<>();
    public Server(){
        try {
            System.out.println("服务器正在启动。。");
            serverSocket = new ServerSocket(8088);
            System.out.println("服务器启动成功！");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void start(){
        while (true){
            try {
                System.out.println("等待客户端连接...");
                Socket socket = serverSocket.accept();
                System.out.println("一个客户端连接了!");

                ClientHandler handler = new ClientHandler(socket);
                Thread t = new Thread(handler);
                t.start();
            } catch (IOException e) {
            }

        }
    }

    public static void main(String[] args) {
        Server server  =new Server();
        server.start();
    }

    private class  ClientHandler implements Runnable{
        private Socket socket;
        private String host;
        private String nickName;
        public ClientHandler(Socket socket){
            this.socket = socket;
            host = socket.getInetAddress().getHostAddress();
        }
        public void run(){
            PrintWriter pw = null;

            try {
                //输入流读取哭护短发送的消息
                InputStream in = socket.getInputStream();
                InputStreamReader isr = new InputStreamReader(in,StandardCharsets.UTF_8);
                BufferedReader br = new BufferedReader(isr);

                //输出流发哦那个消息给客户端
                OutputStream out = socket.getOutputStream();
                OutputStreamWriter osw = new OutputStreamWriter(out,StandardCharsets.UTF_8);
                BufferedWriter bw = new BufferedWriter(osw);
                pw = new PrintWriter(bw,true);

                nickName = br.readLine();
                allout.put(nickName,pw);
                sendMessageToAll("上线了，当前在线人数"+allout.size());


                String message;
                while ((message= br.readLine())!=null){
                    if (message.startsWith("@")){
                        sendMessageToSomeone(message);
                    }else {
                        sendMessageToAll("说：" + message);
                    }
                }
            } catch (IOException e) {
            }finally {
                synchronized (allout){
                allout.remove(nickName);
                }
                sendMessageToAll("下线了，当前在线人数"+allout.size());
                try {
                    socket.close();
                } catch (IOException e) {
                }
            }
        }
        private void sendMessageToAll (String message) {
        System.out.println(nickName+"["+host+"]"+message);
        synchronized (allout) {//与增删互斥
            for (PrintWriter o : allout.values()) {
                o.println(nickName + "[" + host + "]" + message);
            }
        }
        }

        private void sendMessageToSomeone(String message){
            if(message.matches("@.+:.+")){
                String toNickName = message.substring(1,message.indexOf(":"));
                if (allout.containsKey(toNickName)){
                    PrintWriter pw = allout.get(toNickName);
                    String toMessage = message.substring(message.indexOf(":")+1);
                    pw.println(nickName+"悄悄对你说"+toMessage);
                }else {
                    PrintWriter pw = allout.get(nickName);
                    pw.println(toNickName+"用户不在线");
                }
            }else {
                PrintWriter pw = allout.get(nickName);
                System.out.println("私聊格式有误");
            }
        }
    }
}
